/**
 * Persist the current page, dialog and internal page of JQuery Mobile
 *
 * @author Naxan
 */
 
var WebappPersistant = new (function() {
	var currentPage;
	var currentIPage;
	var currentDialog;
	var status = 'init';
	var init = false;
	var data = {};
	
	this.getDialogPersisted = function() {
		return currentDialog;
	}
	
	this.isRunning = function() {
		return (status != 'loaded');
	}
	
	function onChangePage(e, page) {
		if (!page.options.target) {
			loaded = true;
			return; // Start of the application
		}
		
		var url = page.absUrl;
		
		if (page.options.role == "dialog") {
			currentDialog = page.options.target;
		}
		else if (url.indexOf("#") >= 0) { // Internal page
			currentIPage = url.substr(url.indexOf("#"));
		}
		else {
			currentPage = url;
			currentIPage = "";
			currentDialog = "";
			data = {};
		}		
		save();
	}
	
	function showDialog(page) {
		$.mobile.changePage(page, {transition: 'none', role: 'dialog'});
		$(page).trigger("pagepersistant", data);
	}
	
	function onReady(e) {
		load();
		if (!init && currentPage) {
			var href = currentPage;
			if (currentIPage) {
				href += currentIPage;
			}
			
			if (location.href != href) {
				status = 'loading';
				e.preventDefault();
				save();
				location = href;
			}
			else {
				status = 'pageloaded';
				save();
			}
			init = true;
		}
		else if (!init && !currentPage && currentDialog) {
			status = 'pageloaded';
			init = true;
		}
	}
	
	function load() {
		if (localStorage['JQMWebAppPersistant']) {
			var o = JSON.parse(localStorage['JQMWebAppPersistant']);
			currentPage = o.currentPage;
			currentIPage = o.currentIPage;
			currentDialog = o.currentDialog;
			data = o.data;
			status = o.status;
		}
	}
	
	function save() {
		localStorage['JQMWebAppPersistant'] = JSON.stringify({
			currentPage: currentPage,
			currentIPage: currentIPage,
			currentDialog: currentDialog,
			data: data,
			status: status
		});
	}
	
	this.setData = function(o, erase) {
		if (erase || !data) {
			data = {};
		}
		if (typeof(o) == "object" && o) {
			for (var i in o) {
				data[i] = o[i];
			}
		}
		save();
	}
	
	function onBeforeShow(e) {
		if (status == 'pageloaded' || status == 'dialogLoading') {
			var page = $(this);
			$(page).trigger('pagepersistant', [data, (status == 'dialogLoading')]);
			if (currentDialog && status != 'dialogLoading') {
				status = 'dialogLoading';
			}
			else {
				status = 'loaded';
			}
			save();			
		}
	}
	
	function onShow(e) {
		if (status == 'dialogLoading') {
			window.setTimeout(function() { showDialog(currentDialog) }, 250);
		}
	}
	
	$(document).on("pagechange", onChangePage);
	$(document).on("pagebeforechange", onReady);
	$(document).on("pagebeforeshow", ".ui-page", onBeforeShow);
	$(document).on("pageshow", onShow);

});